package NG::Chat::Client::Query;
use strict;
use warnings;

use NG::Sys::Cfg;
use NG::Sys::Sock qw(InetConnect);
use NG::Chat::Client::Message qw(HttpRequest HttpParse);

sub new {
    my $class = shift;
	my $app = shift;
	my $cfg = config("chat_query");
	my %self = (
			%{$cfg->{'http-connect'}},
			logger => $app->logger,
			login => $cfg->{chat_login},
			pass => $cfg->{chat_pass},
			rid => 0,
		);
    my $self = bless \%self, $class;
    return $self;
}
sub logger {
	my $self = shift;
	return $self->{logger};
}
sub send_message {
	my $self = shift;
	my $obj = shift;
	$obj->{login} = $self->{login};
	$obj->{pass} = $self->{pass};
	my $to_send = HttpRequest($self,$obj);
	LOOP:
	for(;;) {
		my $sock;
		my $try = 0;
		my $last_error = "";
		until($sock = InetConnect($self->{peer},$self->{port},1)){
			$last_error = "'$@' '$!'";
			if(++$try >= 60){
				$self->logger->warning("cannot connect to $self->{peer}:$self->{port} for $try times");
				return undef;
			}
			sleep 1;
		}
		if($try > 10){
			$self->logger->warning("connected to $self->{peer}:$self->{port} with $try ".$last_error);
		}
		unless($sock->send($to_send)){
			next;
		}
		my $msg = "";
		my $res;
		do {
			my $buf;
			$sock->recv($buf,1024);
			unless($buf){
				next LOOP;
			}
			$msg .= $buf;
		} until($res = HttpParse(\$msg));
		
		return $res;
	}
}

1;
